package top.kaoshanji.ch02;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.ch02.objectStream.Employee;
import top.kaoshanji.ch02.objectStream.Manager;

import java.io.*;

/**
 * 代码清单 ch02-03：对象序列化示例(2.3.1节)
 * 这些类必须实现 Serializable 接口
 * author kaoshanji
 * ^_^
 * create time 2024/12/6 16:48
 */
public class ObjectStreamTest {

    private static final Logger logger = LogManager.getLogger(ObjectStreamTest.class);

    static final String EMPLOYEE_FILE_NAME = "ch02-03-employee.dat";


    public static void main(String[] args) throws IOException, ClassNotFoundException {
        logger.info("...代码清单 ch02-03：对象序列化示例(2.3.1节)...");

        // 秘书
        var harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
        // 经理1
        var carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
        carl.setSecretary(harry);
        // 经理2
        var tony = new Manager("Tony Tester", 40000, 1990, 3, 15);
        tony.setSecretary(harry);

        // 两个经理共用一个秘书
        var staff = new Employee[3];

        staff[0] = carl;
        staff[1] = harry;
        staff[2] = tony;

        // 将所有对象保存到数据文件里
        try (var out = new ObjectOutputStream(new FileOutputStream(EMPLOYEE_FILE_NAME))){
            out.writeObject(staff);
        }

        // 从文件里读取对象记录
        try (var in = new ObjectInputStream(new FileInputStream(EMPLOYEE_FILE_NAME))){

            // 返回记录的数组
            var newStaff = (Employee[])in.readObject();

            // 第二个元素是 秘书
            newStaff[1].raiseSalary(10);

            // 打印所有的记录
            for (Employee e: newStaff) {
                System.out.println(e);
            }
        }


    }

}
